package com.heima.behavior.service.impl;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {

        //判断userid是否为空
        if (userId != null) {
            Query query = Query.query(Criteria.where("refid").is(userId).and("type").is(ApBehaviorEntry.Type.USER.getCode()));
            ApBehaviorEntry entry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (entry == null) {
                entry= new ApBehaviorEntry();
                entry.setCreatedTime(new Date());
                entry.setType(ApBehaviorEntry.Type.USER.getCode());
                entry.setRefId(userId);
                mongoTemplate.save(entry);

            }
            return entry;
        }
        if (equipmentId != null) {
            Query query = Query.query(Criteria.where("refid").is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT));
            ApBehaviorEntry entry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (entry == null) {
                entry= new ApBehaviorEntry();
                entry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                entry.setCreatedTime(new Date());
                entry.setRefId(equipmentId);
                mongoTemplate.save(entry);

            }
            return entry;
        }
        return null;
    }
}
